<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="dataTreeParams" :inline="true" style="display: flex; justify-content: space-between">
            <el-form-item label="年-月" prop="contrastDate">
              <el-date-picker value-format="YYYY-MM" v-model="dataTreeParams.contrastDate" type="month" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button icon="BottomRight" plain color="green" @click="inherit" v-hasPermi="['budget:contrast:inherit']">继承 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-row :gutter="20">
      <!--    部门-->
      <el-col :lg="7" :xs="24">
        <el-card shadow="never">
          <el-input v-model="deptName" placeholder="请输入预算/用友部门名称" prefix-icon="Search" clearable style="margin-bottom: 10px" />
          <el-tree
            ref="deptListTreeRef"
            class="filter-tree"
            node-key="id"
            :data="deptList"
            :props="defaultProps"
            :expand-on-click-node="true"
            :filter-node-method="filterNode"
            :highlight-current="true"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="17" :xs="24">
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['budget:contrast:add']"> 新增 </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['budget:contrast:remove']"
                  >删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table border v-loading="loading" :data="contrastList" @selection-change="handleSelectionChange" class="enhanced-table">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主键id" align="center" prop="id" v-if="false" />
            <el-table-column label="年/月" align="center" prop="contrastDate" />
            <el-table-column label="部门编码" align="center" prop="friendDeptCode" />
            <el-table-column label="部门名称" align="center" prop="friendDeptName" show-overflow-tooltip />
            <el-table-column label="院区" align="center" prop="yardName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['budget:contrast:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 继承弹窗 -->
    <el-dialog :title="extendDialog.title" v-model="extendDialog.visible" stripe width="400px" append-to-body>
      <el-form ref="inheritFormRef" :model="inheritData">
        <el-form-item label="继承年月" prop="inheritDate">
          <el-date-picker v-model="inheritData.inheritDate" type="month" value-format="YYYY-MM" />
        </el-form-item>
        <el-form-item label="目标年月" prop="targetDate">
          <el-date-picker v-model="inheritData.targetDate" type="month" value-format="YYYY-MM" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="text-center">
          <el-button type="primary" :loading="buttonLoading" @click="saveInherit">确定</el-button>
          <el-button @click="cancelInherit">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-model="dialog.visible" direction="rtl" :title="dialog.title" append-to-body size="1000">
      <el-card shadow="never" style="margin-bottom: 10px">
        <el-form :model="dataDept" :inline="true">
          <el-form-item label="院区" prop="yardCode">
            <el-select v-model="dataDept.yardCode" clearable style="width: 170px" placeholder="全部">
              <el-option v-for="dict in yard_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="dataDept.name" placeholder="请输入部门名称" clearable @keyup.enter="handleSearch" style="width: 170px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" @click="resetRefresh">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-bottom: 10px">
        <el-table border :data="friendDeptList" @selection-change="selectionChange" class="enhanced-table">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="部门编号" align="center" prop="code" />
          <el-table-column label="部门名称" align="center" prop="name" min-width="200" show-overflow-tooltip />
          <el-table-column label="院区" align="center" prop="yardName" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
          <el-table-column label="更新时间" align="center" prop="updateTime" width="180" />
        </el-table>
        <pagination
          v-show="totalSub > 0"
          :total="totalSub"
          v-model:page="dataDept.pageNum"
          v-model:limit="dataDept.pageSize"
          @pagination="getDeptList"
        />
      </el-card>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="contrastDept" lang="ts">
import { addContrast, delContrast, getDeptListTree, listContrast, saveInheritData, verify } from '@/api/budget/contrastDept';
import { AddListDTO, AddListFriendDTO, ContrastQuery, ContrastVO, DeptListTreeVO, InheritData } from '@/api/budget/contrastDept/types';
import { FriendDeptQuery, FriendDeptVO } from '@/api/budget/friendDept/types';
import { listFriendDeptPage } from '@/api/budget/friendDept';
import useDate from '@/hooks/useDate';
import { ElTree } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { yard_type } = toRefs<any>(proxy?.useDict('yard_type'));

// 用友部门列表
const friendDeptList = ref<FriendDeptVO[]>([]);

const contrastList = ref<ContrastVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);

const showSearch = ref(true);
//选择的id列表
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

//弹窗分页
const totalSub = ref(0);

const queryFormRef = ref<ElFormInstance>();

const inheritFormRef = ref<ElFormInstance>();

//对照列表查询参数
const dataTreeParams = reactive<ContrastQuery>({
  deptCode: undefined,
  contrastDate: useDate.getNow(),
  deptName: undefined
});

//选中的树形数据
const selectDept = ref<DeptListTreeVO>();

// =============================================左侧树形部门==============================================================
// 左侧部门查询
const deptName = ref('');
//树形表
const deptListTreeRef = ref<ElTreeInstance>();

//树形数据
const deptList = ref<DeptListTreeVO[]>([]);

const defaultProps = {
  id: 'id',
  children: 'children',
  label: 'label'
};

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.deptName.includes(value);
};

/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptListTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  await getDeptListTree(dataTreeParams).then((res) => {
    deptList.value = res.data;
  });
  if (deptList.value.length === 0) {
    return;
  } else {
    loading.value = true;
    await nextTick();

    let firstElement: DeptListTreeVO = deptList.value[0];
    if (firstElement) {
      // 默认选中第一个
      deptListTreeRef.value.setCurrentKey(firstElement.id);
      selectDept.value = firstElement;
      dataTreeParams.deptCode = firstElement.deptCode;
      if (firstElement.children != null) {
        //右侧列表
        await getList();
      }
    }
  }
};

/** 节点单击事件 */
const handleNodeClick = (data: DeptListTreeVO) => {
  if (data.level === 2) {
    return;
  }
  // 选中的数据
  selectDept.value = data;
  //左侧列表参数
  dataTreeParams.deptCode = data.deptCode;
  getList();
};

//==========================================================继承===========================================================
// 继承弹窗按钮开关
const extendDialog = reactive<DialogOption>({
  visible: false,
  title: '部门对照继承'
});

// 继承数据
const inheritData = reactive<InheritData>({
  inheritDate: undefined,
  targetDate: undefined,
  type: 1
});

// 重置继承数据
const resetInheritData = () => {
  inheritData.inheritDate = undefined;
  inheritData.targetDate = undefined;
};

// 继承按钮
const inherit = () => {
  extendDialog.visible = true;
  inheritData.inheritDate = useDate.getPreviousMonth();
  inheritData.targetDate = useDate.getNow();
};

// 确认继承
const saveInherit = async () => {
  buttonLoading.value = true;
  let msg: string;
  await verify(inheritData)
    .then((res) => {
      if (res.data === 1) {
        msg = '继承年月无数据!';
      }
      if (res.data === 2) {
        msg = '目标年月已存在对照数据,是否覆盖?';
      }
      if (res.data === 3) {
        msg = '目标年月无对照数据,是否继承?';
      }
    })
    .then(() => {
      proxy?.$modal
        .confirm(msg)
        .then(() => {
          saveInheritData(inheritData);
          proxy?.$modal.msgSuccess('操作成功');
          extendDialog.visible = false;
        })
        .then(() => {
          getTreeSelect();
        })
        .catch(() => {
          cancelInherit();
        });
    })
    .finally(() => (buttonLoading.value = false));
};

// 取消继承
const cancelInherit = () => {
  resetInheritData();
  extendDialog.visible = false;
};
// ======================================================右侧对照部门=====================================================
/** 查询部门对照列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContrast(dataTreeParams);
  contrastList.value = res.data;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getTreeSelect();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ContrastVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 用友数据查询参数
const dataDept = reactive<FriendDeptQuery>({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  yardCode: undefined,
  deptCode: undefined,
  contrastDate: undefined
});
// 添加弹窗按钮开关
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
/** 新增按钮操作 */
const handleAdd = () => {
  if (!selectDept.value) {
    proxy?.$modal.msgWarning('请选择左侧部门');
  } else {
    //清空选择的列表数据
    friendList.value = [];
    contrastDTO.value.list = [];
    dialog.visible = true;
    dialog.title = '用友部门';
    dataDept.deptCode = selectDept.value.deptCode;
    dataDept.contrastDate = dataTreeParams.contrastDate;
    getDeptList();
  }
};
/** 删除按钮操作 */
const handleDelete = async (row?: ContrastVO) => {
  if (row) {
    ids.value = [];
    ids.value.push(row.id);
  }
  await proxy?.$modal.confirm('是否确认删除选中的数据项？').finally(() => (loading.value = false));
  await delContrast(ids.value);
  proxy?.$modal.msgSuccess('删除成功');
  await getTreeSelect();
};
//====================================================弹窗用友部门===========================================================
//用友部门列表
const friendList = ref<FriendDeptVO[]>([]);
//用友部门
const getDeptList = async () => {
  loading.value = true;
  const res = (await listFriendDeptPage(dataDept)).data;
  friendDeptList.value = res.records;
  totalSub.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleSearch = () => {
  dataDept.pageNum = 1;
  getDeptList();
};

/** 重置按钮操作 */
const resetRefresh = () => {
  // 查询条件参数重置
  dataDept.name = undefined;
  dataDept.yardCode = undefined;
  handleSearch();
};

//添加时选择的用友部门
const contrastDTO = ref<AddListDTO>({
  deptCode: undefined,

  deptName: undefined,

  contrastDate: dataTreeParams.contrastDate,

  list: []
});

const selectionChange = (selection: FriendDeptVO[]) => {
  friendList.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 模型重置 */
const reset = () => {
  contrastDTO.value.deptName = undefined;
  contrastDTO.value.deptCode = undefined;
  contrastDTO.value.contrastDate = undefined;
  contrastDTO.value.list = [];
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
/** 提交按钮 */
const submitForm = async () => {
  if (friendList.value.length === 0) {
    proxy?.$modal.msgWarning('请选择用友部门');
  } else {
    buttonLoading.value = true;
    contrastDTO.value.deptName = selectDept.value.deptName;
    contrastDTO.value.deptCode = selectDept.value.deptCode;
    contrastDTO.value.contrastDate = dataTreeParams.contrastDate;
    friendList.value.map((item) => {
      contrastDTO.value.list.push(new AddListFriendDTO(item.code, item.name, item.yardName));
    });

    await addContrast(contrastDTO.value).finally(() => (buttonLoading.value = false));
    proxy?.$modal.msgSuccess('操作成功');
    dialog.visible = false;
    await getTreeSelect();
  }
};

//====================================================================================================================
onMounted(() => {
  //树形列表
  getTreeSelect();
});
</script>

<style lang="scss" scoped>
.my-class {
  margin-top: 20px;
}

.my-class-1 {
  margin-top: 40px;
}

:deep(.el-tree) {
  /* 整体样式 */
  background: #f8f9fa; /* 背景色 */
  color: #333; /* 文字颜色 */
  font-size: 14px;
  border-radius: 4px;
  padding: 10px;
}

/* 节点高度调整 */
:deep(.el-tree-node) {
  margin: 3px 0;
}

/* 节点悬停效果 */
:deep(.el-tree-node__content:hover) {
  background-color: #e6e6fa !important;
  border-radius: 5px;
}

/* 选中/高亮状态 */
:deep(.el-tree-node:focus > .el-tree-node__content, .el-tree-node.is-current > .el-tree-node__content) {
  background-color: #87cefa !important;
  color: #ff1493;
  font-weight: bolder;
  border-radius: 5px;
}

/* 展开/折叠图标优化 */
:deep(.el-tree-node__expand-icon) {
  color: #6495ed;
  font-size: 16px;
  transition: transform 0.3s;
}

/* 展开图标旋转 */
//:deep(.el-tree-node__expand-icon.expanded) {
//  transform: rotate(90deg);
//}

/* 层级线样式（需开启 show-line 属性） */
:deep(.el-tree--line .el-tree-node::before) {
  border-left: 1px dashed #adb5bd;
}

:deep(.el-tree--line .el-tree-node::after) {
  border-top: 1px dashed #adb5bd;
}

/* 节点标签样式 */
:deep(.el-tree-node__label) {
  font-size: 14px;
  padding-left: 6px;
}

/* 复选框样式 */
:deep(.el-checkbox__inner) {
  border-radius: 3px;
}

/* 节点间距调整 */
:deep(.el-tree-node__content) {
  height: 28px; /* 节点高度 */
  line-height: 28px;
}
</style>
